package com.hundsun.cprs.yyt.service.dilivery.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.service.dilivery.domain.query.SynQuery;
import com.hundsun.cprs.yyt.service.dilivery.service.Kuaidi100Service;
import com.hundsun.cprs.yyt.util.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

@Service
public class Kuaidi100ServiceImpl extends BaseService implements Kuaidi100Service {

    @Value("${kuaidi100.customer}")
    private String customer; // 从配置文件加载

    @Value("${kuaidi100.key}")
    private String key; // 从配置文件加载

    @Value("${kuaidi100.queryUrl}")
    private String queryUrl; // 从配置文件加载

    @Autowired
    PooledHttpClientAdaptor adaptor;

    @Override
    public String synQueryData(SynQuery synQuery) {
        // 参数校验
        if(synQuery==null){
            Assert.notNull(synQuery,"synQuery不能为空");
        }
        if(StringUtils.isEmpty(synQuery.getCom())){
            Assert.hasText(synQuery.getCom(),"快递公司编码com参数必填");
        }
        if(StringUtils.isEmpty(synQuery.getNum())){
            Assert.hasText(synQuery.getNum(),"快递单号num参数必填");
        }
        // 标识不为1的全设置为0
        if(synQuery.getResultv2()!=1){
            synQuery.setResultv2(0);
        }
        String jsonStr = JSONObject.toJSONString(synQuery);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("customer", this.customer);
        String sign = MD5Utils.encode(jsonStr + this.key + this.customer);
        params.put("sign", sign);
        params.put("param", jsonStr);
        return adaptor.doPost(queryUrl,params);
    }
}
